package com.laiqilin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laiqilin.entity.Content;
import com.laiqilin.entity.ContentCategory;
import com.laiqilin.service.IContentService;
import com.laiqilin.mapper.ContentMapper;
import com.laiqilin.utils.PageResult;
import com.laiqilin.vo.ContentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements IContentService {

    @Autowired
    private ContentCategoryService contentCategoryService;

    /**
     * 根据条件搜索内容
     *
     * @param page 当前页
     * @param pageSize 每页大小
     * @param vo 内容查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<Content> search(Integer page, Integer pageSize, ContentVO vo) {

        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        // 根据标题模糊查询
        wrapper.like(StrUtil.isNotBlank(vo.getTitle()), "e_name", vo.getTitle());
        // 根据分类ID查询
        wrapper.eq(vo.getCategoryId() != null, "e_depart", vo.getCategoryId());

        // 分页查询
        Page<Content> page1 = this.page(new Page<>(page, pageSize), wrapper);

        // 给每个内容添加分类名称
        page1.getRecords().forEach(content -> {
            ContentCategory contentCategory = contentCategoryService.getById(content.getCategoryId());
            content.setName(contentCategory.getName());
        });

        return new PageResult<>(page1.getRecords(), page1.getTotal());
    }

    /**
     * 添加新内容
     *
     * @param content 新内容
     * @return 是否添加成功
     */
    @Override
    public boolean add(Content content) {
        return this.save(content);
    }
}
